package com.weiiew.backend.executor;

import com.weiiew.backend.entity.config.MouseClickConfig;
import com.weiiew.backend.entity.enums.LogState;
import com.weiiew.backend.exception.ExecutorParamsException;
import com.weiiew.backend.operation.DelayOperation;
import com.weiiew.backend.operation.MouseMove;
import com.weiiew.backend.operation.MousePress;
import com.weiiew.backend.operation.MouseRelease;
import com.weiiew.backend.operationUtils.MouseCode;
import com.weiiew.backend.operationUtils.OperationSequence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 鼠标连点配置执行器，封装了状态转化保证了多线程的安全性
 *
 * @author 魏锴
 * @since 2025/4/27
 */
@Slf4j
@Component
public class MouseClickExecutor extends baseExecutor<MouseClickConfig> {

    @Override
    protected void initResource(MouseClickConfig config) throws ExecutorParamsException {
        System.out.println(config);
        if (config.getClickButton() == null) throw new ExecutorParamsException("配置错误");
        executor.setOperations(getSequence(config));
        executor.setTerminationPolicy(config.getStop());
        executor.setLogger(messagingTemplate, config.getChannel());
        executor.setLogState(LogState.SEQUENCE);
    }

    @Override
    protected void clearResource() {
    }

    public OperationSequence getSequence(MouseClickConfig config) {
        OperationSequence operations = new OperationSequence();
        if (config.getPosition().getType().equals("manual")) {
            operations.addOperation(new MouseMove(config.getPosition().getX(), config.getPosition().getY(), 0));
        }
        MouseCode mouseCode = MouseCode.LEFT;
        if ("right".equals(config.getClickButton())) mouseCode = MouseCode.RIGHT;
        else if ("middle".equals(config.getClickButton())) mouseCode = MouseCode.MIDDLE;
        operations.addOperation(new MousePress(mouseCode, 0)); // 点击操作
        operations.addOperation(new MouseRelease(mouseCode, config.getClickDuration())); // 释放操作
        operations.addOperation(new DelayOperation(config.getInterval() + config.getClickDuration())); // 延迟操作
        if ("double".equals(config.getClickCount())) {
            operations.addOperation(new MousePress(mouseCode, config.getInterval() + config.getClickDuration())); // 点击操作
            operations.addOperation(new MouseRelease(mouseCode, config.getInterval() + config.getClickDuration() * 2)); // 释放操作
            operations.addOperation(new DelayOperation((config.getInterval() + config.getClickDuration()) * 2)); // 延迟操作
        }
        return operations;
    }
}
